from IPython.utils import data
from flask import current_app
from flask import g, jsonify
from flask import render_template
from flask import request
from flask import session
from sqlalchemy.sql.functions import user

from info import constants
from info import db
from info.models import Category, News
from info.modules.profile import profile_blu
from info.response_code import RET
from info.utils.common import login_user_data
from info.utils.image_storage import storage


@profile_blu.route('/info')
@login_user_data
def user_info():
    user = g.user
    return render_template('news/user.html',data={'user_info':user.to_dict() if user else None})


"""
POST请求修改数据  基本资料
1.接受数据
2.效验数据(是否都传递过来)
3.更新数据
4.返回响应
"""
@profile_blu.route('/base_info',methods=['POST','GET'])
@login_user_data
def user_base_info():
    user = g.user

    if not user:
        return jsonify(errno=RET.SESSIONERR ,errmsg='没有登陆')

    if request.method == 'GET':
        return render_template('news/user_base_info.html',data={'user_info':user.to_dict() if user else None})

    else:
         # 1.接受数据
        nick_name = request.json.get('nick_name')
        gender = request.json.get('gender')
        signature = request.json.get('signature')
        # 2.效验数据

        if not all([nick_name,gender,signature]):
            return jsonify(errno=RET.PARAMERR ,errmsg='参数不全')


        if gender not in ['MAN','WOMAN']:
            return jsonify(errno=RET.PARAMERR ,errmsg='性别数据错误')
        # 3.更新数据
        user.nick_name = nick_name
        user.gender = gender
        user.signature = signature

        # 更新session中的数据
        session['nick_name'] = nick_name
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
        # 4.返回响应
        return jsonify(errno=RET.OK ,errmsg='ok')



"""
POST上传图片
1.接收数据（图片）
2.上传到七牛云中，获取到返回的图片名字
3.更新用户的头像信息
4.返回响应

"""
@profile_blu.route('/pic_info',methods=['POST','GET'])
@login_user_data
def user_pic_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pic_info.html',data={'user_info':user.to_dict() if user else None})


# 1.接收数据（图片）  avatar 头像
    avatar = request.files.get('avatar')
    if not avatar:
        return jsonify(errno=RET.PARAMERR ,errmsg='参数错误')
# 2.上传到七牛云中，获取到返回的图片名字
    try:
        # 调用read方法
        data = avatar.read()
        # 调用七牛云的储存
        path = storage(data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR ,errmsg='上传失败')
# 3.更新用户的头像信息
    user.avatar_url = path
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
# 4.返回响应
    return jsonify(errno=RET.OK ,errmsg='ok',data={'avatar_url':constants.QINIU_DOMIN_PREFIX + path})




"""
修改密码 POST
1.接受参数
2.三个参数都必须有
3.两次密码必须一致
4.查询用户  当前的密码是否正确
5.修改密码
6.返回响应


"""



"""
# 1.先接受分页参数page  per_page
# 2.查询数据
#     模型类名.query.paginite()
# 3.传递给模板进行展示
:return:
"""
@profile_blu.route('/collection')
@login_user_data
def user_collection():

    user = g.user
    # 1.先接受分页参数page  per_page
    try:
        page = request.args.get('page','1')
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    # 2.查询数据
    try:
        #     模型类名.query.paginite()
        paginate = user.collection_news.paginate(page=page,per_page=2)
        # 当前页码的所有数据
        items = paginate.items
        # 获取当前页码
        current_page = paginate.page
        # 总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR ,errmsg='获取数据失败')
    collections = []
    for item in items:
        collections.append(item.to_basic_dict())

    # 3.传递给模板进行展示
    return render_template('news/user_collection.html',
                           collections = collections,
                           current_page = current_page,
                           total_page = total_page)





@profile_blu.route('/news_release',methods=['POST','GET'])
@login_user_data
def user_news_release():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR ,errmsg='用户未登录')
    if request.method == 'GET':
        # 获取分类信息
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        # 把查询出来的对象列表转换为字典列表
        categories_list = []
        for item in categories:
            categories_list.append(item.to_dict())


        # 这里有一个小问题：需要把最新的数据   删除
        categories_list.pop(0)


        return render_template('news/user_news_release.html',
                               data={'categories':categories_list})

    """
    POST获取发布是新闻数据
    1.接受参数
    2.参数进行效验，必须都传递尽来
    3.图片的单独处理，我们保存的是图片的url我们先把图片上传到七牛云中
    4.新增新闻
    5.保存到数据库
    6.返回

    """
    # 1.接受参数
    title = request.form.get('title')                 # 标题
    category_id = request.form.get('category_id')     # 分类id
    content = request.form.get('content')             # 内容
    digest = request.form.get('digest')               # 摘要
    index_image = request.files.get('index_image')    # 图片文件

    # 2.参数进行效验，必须都传递尽来
    if not all({title,category_id,content,digest,index_image}):
        return jsonify(errno=RET.PARAMERR ,errmsg='参数不全')
    # 3.图片的单独处理，我们保存的是图片的url我们先把图片上传到七牛云中
    try:
        data = index_image.read()
        path = storage(data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR ,errmsg='上传失败')
    # 4.新增新闻
    news = News()
    news.title = title
    news.source = '个人'
    news.digest = digest
    news.content = content
    news.category_id = category_id
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + path
    news.user_id = user.id
    news.status = 1  # 0代表审核通过  1 代表审核中  -1 代表审核不通过
    # 5.保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()

    # 6.返回
    return jsonify(errno=RET.OK ,errmsg='ok')


# 数据加载及模板显示
@profile_blu.route('/news_list')
@login_user_data
def news_list():

    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_news_list.html', data=data)


"""
关注于取消关注
1.获取参数
2.进行分页
3.返回数据
"""
@profile_blu.route('/user_follow')
@login_user_data
def follow_list():
    user = g.user
    try:
        p = request.args.get('p','1')
        p = int(p)
    except Exception as e:

        current_app.logger.error(e)
        p=1
    try:
        paginate = user.followers.paginate(page=p,per_page=2)
        items = paginate.items
        current_page = paginate.page
        total_page = paginate.pages   # 总页数
    except Exception as e:
        return jsonify(errno=RET.DBERR ,errmsg='没有数据')

    follows = []
    for item in items:
        follows.append(item.to_dict())

    data = {

        'current_page':current_page,
        'total_page':total_page,
        'users':follows
    }

    return render_template('news/user_follow.html',data=data)